package ls.ch01.demo7;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author ls
 * @Date 创建时间:2022/4/4 19:03
 * 描述:
 */

public class Demo7 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InvocationTargetException {
        Class clz = Class.forName("com.ls.ch01.demo1.Person");
        //获取Person的无参构造：public Person()
        Constructor c1 = clz.getDeclaredConstructor();
        //Person的无参构造为public，这里可以直接访问
        Object obj = c1.newInstance();
        System.out.println(obj);

        //获取Person的单参构造：private Person(String)
        Constructor c2 = clz.getDeclaredConstructor(String.class);
        //Person的单参构造为private，这里已超出其访问范围，不能直接访问
        //通过setAccessable方法，设定为可以访问
        c2.setAccessible(true);
        obj = c2.newInstance("New Person");
        System.out.println(obj);

        //获取Person的三参构造：protected Person(String ,String, String)
        Constructor c3 = clz.getDeclaredConstructor(String.class, String.class, String.class);
        //Person 的三参构造为protected，这里已超出其访问范围，不能直接访问
        //通过setAccessable方法，设定为可以访问
        c3.setAccessible(true);
        obj = c3.newInstance("New Person", "beijing", "Hello!");
        System.out.println(obj);
    }
}
